package com.yy.watchmen;


import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.text.TextUtils;
import android.util.Log;

import java.util.List;

public class AppUtils {

    public static void launchApp(Context context, final String packageName) {
        Log.e("WatchmenService","launchApp " + packageName);
        Intent launchAppIntent = getLaunchAppIntent(context, packageName);
        if (launchAppIntent != null) {
            Log.e("WatchmenService","启动 " + packageName);
            context.startActivity(launchAppIntent);
        }
    }

    public static Intent getLaunchAppIntent(Context context, final String pkgName) {
        String launcherActivity = getLauncherActivity(context, pkgName);
        Log.e("WatchmenService","launcherActivity：" + launcherActivity);
        if (TextUtils.isEmpty(launcherActivity)) {
            return null;
        }
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClassName(pkgName, launcherActivity);
        return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    public static String getLauncherActivity(Context context, String pkg) {
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(pkg);
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> info = pm.queryIntentActivities(intent, 0);
        if (info.size() == 0) {
            return "";
        }
        return info.get(0).activityInfo.name;
    }
}
